﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Gencode.Gengui.Wizzard;

namespace Gencode.PrsUtil.InitWizard
{
    [ToolboxItem(false)]
	public partial class InitYear : Gencode.Gengui.Wizzard.WizzardControl
	{
		public InitYear(string previousControl, string nextControl, WizzardDialog controler)
			: base(previousControl, nextControl, controler)
		{
			InitializeComponent();
			InitializeComboYear();
		}

		private void InitializeComboYear()
		{
			// Check if ther are any old jears
			int maxJahr = Gencode.PrsCommon.Data.Plan.PlanData.GetMaxYear();

			if (maxJahr == 0)
				maxJahr = DateTime.Today.Year - 1;

			maxJahr++;
			for (int i = 0; i < 10; i++)
			{
				comboJear.Items.Add("" + maxJahr);
				maxJahr++;
			}
		}

		public override bool MoveNext()
		{
			if (comboJear.SelectedIndex >= 0)
			{
				string von = Convert.ToString(Gencode.PrsCommon.App.DateUtil.ToInt("01.01." + comboJear.Text));
				string bis = Convert.ToString(Gencode.PrsCommon.App.DateUtil.ToInt("31.12." + comboJear.Text));
				int year = int.Parse(comboJear.Text);

				InitData da = Controler.DataObjects.GetType(typeof(InitData)) as InitData;

				Gencode.PrsCommon.Data.Common.CommonData.CreateJear(year, von, bis, da.Mandid);
				DataView dv = Gencode.Common.SQL.SimpleQuerry.ExecuteForDataView("select wert,textwert from Options where typ = 'Monat' order by wert");
				int month = 0;
				string name = "";
				string mVon = "";
				string mBis = "";

				for (int i = 0; i < dv.Count; i++)
				{
					try
					{
						month = int.Parse(dv[i].Row[0].ToString());
						name = dv[i].Row[1].ToString();
						mVon = SetDateBeginMonth(year, month);
						mBis = SetDateEndMonth(year, month);
					}
					catch (Exception exp)
					{
						Gencode.Common.Util.ErrorHandler.LoggError("Year Error", "CreateYearDlg.createYear()", exp.Message);
					}
					finally
					{
						Gencode.PrsCommon.Data.Plan.PlanData.SaveMonth(year, month, name, mVon, mBis, da.Mandid);
					}
				}

				return true;
			}

			return false;
		}

		private string SetDateBeginMonth(int year, int month)
		{
			string mo;
			if (month < 10)
			{
				mo = "0" + month;
			}
			else
			{
				mo = "" + month;
			}
			return year + "" + mo + "01";
		}

		private string SetDateEndMonth(int year, int month)
		{
			string mo;
			string da;
			int day = DateTime.DaysInMonth(year, month);

			if (month < 10)
			{
				mo = "0" + month;
			}
			else
			{
				mo = "" + month;
			}

			if (day < 10)
			{
				da = "0" + day;
			}
			else
			{
				da = "" + day;
			}
			return year + mo + da;
		}
	}
}
